/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package cart.hibernate.order;

/**
 *
 * @author BibooChung
 */

import java.util.*;
import cart.hibernate.*;

import cart.hibernate.HibernateUtil;
import cart.hibernate.address.*;
import cart.hibernate.paymentMethod.*;
import cart.hibernate.orderStatus.*;
import cart.hibernate.movieInformation.*;
import cart.hibernate.member.*;



import java.util.List; 
import java.util.Iterator; 
import java.util.Set;
import java.util.HashSet;
 
import org.hibernate.HibernateException; 
import org.hibernate.Session; 
import org.hibernate.Transaction;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.HibernateException; 
import org.hibernate.Session; 
import org.hibernate.Transaction;
import org.hibernate.SessionFactory;
import org.hibernate.SQLQuery;
import org.hibernate.Criteria;
import org.hibernate.Hibernate;
import org.hibernate.cfg.Configuration;
public class ManageOrder {
    public static void main(String[] args) {

        Date date = new Date();

        ManageOrder manager = new ManageOrder();
        List list = new ArrayList();
        list.add(4);
        list.add(5);
        
        List listLong = new ArrayList();
        listLong.add((long)36);
        listLong.add((long)37);
        
        manager.addOrder( date, date, 
                 "12345678123415678", 3, 
                 3, "fladdt", "bing", "dasfd",
                 "d", "asdf", listLong, list);


    }


    public List getAllOrder() {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction tx = null;
        List allOrder = null;
        try{
           tx = session.beginTransaction();
           allOrder = session.createQuery("FROM Order").list(); 
           tx.commit();
        }catch (HibernateException e) {
           if (tx!=null) tx.rollback();
           e.printStackTrace(); 
        }finally {
           session.close(); 
        }
        return allOrder;
    }
    
    public long addOrder(Date orderDatetime, Date shippedDatetime, 
                 String creditCardNum, long paymentMethodId, 
                 int orderStatusId, String flat, String blockAndBuilding, String district,
                 String region, String loginName, long movieId, int quantity) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction tx = null;
        long orderId=-1;

        try{
            tx = session.beginTransaction();

            Address address = new Address(flat, blockAndBuilding, district, region);

            MovieInformation movie = (MovieInformation)session.get(MovieInformation.class, movieId); 
            Set<MovieInformation> movieSet = new HashSet<MovieInformation>();
            movieSet.add(movie);
            
            PaymentMethod paymentMethod = (PaymentMethod)session.get(PaymentMethod.class, paymentMethodId); 
            OrderStatus orderStatus = (OrderStatus)session.get(OrderStatus.class, orderStatusId); 
            Member member = (Member)session.get(Member.class, loginName); 
            String pickupPersonName = member.getFirstName() + " " + member.getLastName();
            double price = movie.getUnitPrice();

            
            
            
            Order order = new Order(orderDatetime, shippedDatetime, pickupPersonName,
                 creditCardNum, price, paymentMethod, 
                 orderStatus, address, member);
            order.getMovies().add(movie);
            
            address.setOrder(order);
            
            session.save(order);
            
            orderId = order.getOrderId();
            
            tx.commit();
            tx = session.beginTransaction();
            
            
            String sql = "update order_details set quantity = :quan where movie_id=:mid and order_id=:oid ;";
            //String sql = "update order_details set quantity = 6 where movie_id=6 and order_id=14 ;";
            SQLQuery query = session.createSQLQuery(sql);
            query.addEntity("order_details");
            query.setParameter("quan", quantity);
            query.setParameter("mid", movieId);
            query.setParameter("oid", orderId);

            query.executeUpdate();
            
            tx.commit();
        }catch (HibernateException e) {
           if (tx!=null) tx.rollback();
           e.printStackTrace(); 
        }finally {
           session.close(); 
        }
        return orderId;
    }
    
    public long addOrder(Date orderDatetime, Date shippedDatetime, 
                 String creditCardNum, long paymentMethodId, 
                 int orderStatusId, String flat, String blockAndBuilding, String district,
                 String region, String loginName, List movieId, List quantityList) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction tx = null;
        long orderId=-1;

        try{
            tx = session.beginTransaction();

            Address address = new Address(flat, blockAndBuilding, district, region);

            Set<MovieInformation> movieSet = covertMovieIdToMovieSet(movieId, session);
            
            PaymentMethod paymentMethod = (PaymentMethod)session.get(PaymentMethod.class, paymentMethodId); 
            OrderStatus orderStatus = (OrderStatus)session.get(OrderStatus.class, orderStatusId); 
            Member member = (Member)session.get(Member.class, loginName); 
            String pickupPersonName = member.getFirstName() + " " + member.getLastName();
            
            
            double price = 0;

            ArrayList quantityArrList = new ArrayList(quantityList); 
            int i = 0;
            Iterator iter = movieSet.iterator();
            while(iter.hasNext())
            {
                int quantity = (Integer)(quantityArrList.get(i));
                i++;
               // MovieInformation movie = (MovieInformation)session.get(MovieInformation.class, (Long)iter.next()); 
                price += ((MovieInformation)iter.next()).getUnitPrice() * quantity;
            }
            
            
            
            Order order = new Order(orderDatetime, shippedDatetime, pickupPersonName,
                 creditCardNum, price, paymentMethod, 
                 orderStatus, address, member);
            order.getMovies().addAll(movieSet);
            
            address.setOrder(order);
            
            session.save(order);
            
            orderId = order.getOrderId();
            
            tx.commit();
            tx = session.beginTransaction();
            
            
            quantityArrList = new ArrayList(quantityList);           
            ArrayList movieIdList = new ArrayList(movieId);           
            for (i = 0 ; i < quantityArrList.size() ; i++)
            {
              int quantity = (Integer)(quantityArrList.get(i));
              //MovieInformation movie = new MovieInformation((MovieInformation)session.get(MovieInformation.class, quantity));
              
              String sql = "update order_details set quantity = :quan where movie_id=:mid and order_id=:oid ;";
              //String sql = "update order_details set quantity = 6 where movie_id=6 and order_id=14 ;";
              SQLQuery query = session.createSQLQuery(sql);
              query.addEntity("order_details");
              query.setParameter("quan", quantity);
              query.setParameter("mid", (Long)movieIdList.get(i));
              query.setParameter("oid", orderId);

              query.executeUpdate();
            }
            
            tx.commit();
        }catch (HibernateException e) {
           if (tx!=null) tx.rollback();
           e.printStackTrace(); 
        }finally {
           session.close(); 
        }
        return orderId;
    }
    public static Set covertMovieIdToMovieSet(List idList, Session session){
        Set set = new HashSet();
        ArrayList targetIdList = new ArrayList(idList);           
        for (int i = 0 ; i < targetIdList.size() ; i++)
        {
          long id = (Long)(targetIdList.get(i));
          MovieInformation targetObject = (MovieInformation)session.get(MovieInformation.class, id);
          set.add(targetObject);
        }
      return set;
    }

    public long updateOrder(long orderId, Date orderDatetime, Date shippedDatetime, 
                 String creditCardNum, long paymentMethodId, 
                 int orderStatusId, String flat, String blockAndBuilding, String district,
                 String region, String loginName, List movieId, List quantityList) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction tx = null;
        

        try{
            tx = session.beginTransaction();

            Order order = (Order)session.get(Order.class, orderId); 

            Address address = (Address)session.get(Address.class, orderId);
            address.setAddress(flat, blockAndBuilding, district, region);

          

         //   MovieInformation movie = (MovieInformation)session.get(MovieInformation.class, movieId); 
            Set<MovieInformation> movieSet = covertMovieIdToMovieSet(movieId, session);
        //    movieSet.add(movie);
            
            PaymentMethod paymentMethod = (PaymentMethod)session.get(PaymentMethod.class, paymentMethodId); 
            OrderStatus orderStatus = (OrderStatus)session.get(OrderStatus.class, orderStatusId); 
            Member member = (Member)session.get(Member.class, loginName); 
            String pickupPersonName = member.getFirstName() + " " + member.getLastName();
            

            double price = 0;

            ArrayList quantityArrList = new ArrayList(quantityList); 
            int i = 0;
            Iterator iter = movieSet.iterator();
            while(iter.hasNext())
            {
                int quantity = (Integer)(quantityArrList.get(i));
                i++;
               // MovieInformation movie = (MovieInformation)session.get(MovieInformation.class, (Long)iter.next()); 
                price += ((MovieInformation)iter.next()).getUnitPrice() * quantity;
            }

      
            
            
            order.setOrder(orderDatetime, shippedDatetime, pickupPersonName,
                 creditCardNum, price, paymentMethod, 
                 orderStatus, address, member);
            order.getMovies().clear();
            order.getMovies().addAll(movieSet);
            
            
            //address.setOrder(order);
            session.update(address);
            session.update(order);
            
            
            tx.commit();
            tx = session.beginTransaction();
            
            quantityArrList = new ArrayList(quantityList);           
            ArrayList movieIdList = new ArrayList(movieId);           
            for (i = 0 ; i < quantityArrList.size() ; i++)
            {
              int quantity = (Integer)(quantityArrList.get(i));
              //MovieInformation movie = new MovieInformation((MovieInformation)session.get(MovieInformation.class, quantity));
              
              String sql = "update order_details set quantity = :quan where movie_id=:mid and order_id=:oid ;";
              //String sql = "update order_details set quantity = 6 where movie_id=6 and order_id=14 ;";
              SQLQuery query = session.createSQLQuery(sql);
              query.addEntity("order_details");
              query.setParameter("quan", quantity);
              query.setParameter("mid", (Long)movieIdList.get(i));
              query.setParameter("oid", orderId);

              query.executeUpdate();
            }
            
           
            
            tx.commit();
        }catch (HibernateException e) {
           if (tx!=null) tx.rollback();
           e.printStackTrace(); 
        }finally {
           session.close(); 
        }
        return orderId;
    }






    public void deleteOrder(long orderId) {
      Session session = HibernateUtil.getSessionFactory().openSession();
      Transaction tx = null;
      try{
         tx = session.beginTransaction();
         Order order = (Order)session.get(Order.class, orderId); 
         session.delete(order); 
         tx.commit();
      }catch (HibernateException e) {
         if (tx!=null) tx.rollback();
         e.printStackTrace(); 
      }finally {
         session.close(); 
      }
    }
 
}
